package cn.achao.csr.task.core.job;

import cn.achao.csr.task.core.model.dto.JobFeignDTO;
import cn.achao.csr.task.mapper.XxlJobCommonMapper;
import com.alibaba.fastjson2.JSON;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @Author: achao
 **/
@Slf4j
@Component
@RequiredArgsConstructor
public class SimpleXxlJob {

    private final XxlJobCommonMapper xxlJobCommonMapper;

    @XxlJob("demoJobHandler")
    public void demoJobHandler() {
        log.info("执行定时任务,执行时间:{}", new Date());
    }

    @XxlJob("shardingDemo")
    public void shardingJobHandler() {
        int shardTotal = XxlJobHelper.getShardTotal();
        int shardIndex = XxlJobHelper.getShardIndex();
        log.info("执行分片任务,分片下标【{}】,总分片数【{}】", shardIndex, shardTotal);
    }

    @XxlJob("feignSendTask")
    public void feignSendTask() {
        long jobId = XxlJobHelper.getJobId();
        String param = xxlJobCommonMapper.selectExecutorParamByJobId(jobId);

        if (!JSON.isValid(param)) {
            log.error("非法参数 jobId:{}", jobId);
            return;
        }
        JobFeignDTO jobFeignDTO = JSON.parseObject(param, JobFeignDTO.class);
        Boolean needToken = jobFeignDTO.getNeedToken();
        String severName = jobFeignDTO.getSeverName();
        String apiUrl = jobFeignDTO.getApiUrl();
        String method = jobFeignDTO.getMethod();
        String params = jobFeignDTO.getParams();
        if (needToken) {
            // TODO 获取token
        }
        if (StringUtils.isAnyBlank(severName, method, apiUrl)) {
            log.error("参数缺失 jobId:{} severName【{}】 method【{}】 apiUrl【{}】", jobId, severName, method, apiUrl);
            return;
        }
        log.info("执行feign任务,jobId:{} severName:{} method:{} apiUrl:{} params:{}", jobId, severName, method, apiUrl, params);

    }
}
